﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using WBFSe.OS;

namespace WBFSe.IO
{
    /// <summary>
    /// IO Exception
    /// </summary>
    public class WbfsIOException : IOException
    {
        // Variables

        int errorCode;

        // Properties

        /// <summary>
        /// Win32 error code
        /// </summary>
        public int ErrorCode 
        {
            get { return this.errorCode; }
        }

        // Methods

        /// <summary>
        /// Constructor
        /// </summary>
        public WbfsIOException(int error)
            : base(FormatErrorCode(error))
        {
            this.errorCode = error;
        }

        /// <summary>
        /// Formats the error code to a message
        /// </summary>
        /// <param name="code">Error code</param>
        /// <returns>Formatted message</returns>
        static String FormatErrorCode(int code)
        {
            if (code > 0)
            {
                String sMessage = String.Empty;
                IntPtr pMessage = IntPtr.Zero;
                uint dwChars;

                dwChars = Native.FormatMessage(0x00000100 | 0x00001000 | 0x00000200,
                    IntPtr.Zero, (uint)code, 0, ref pMessage, 0, IntPtr.Zero);

                if (dwChars == 0)
                    return "No message";

                sMessage = Marshal.PtrToStringAnsi(pMessage);
                Native.LocalFree(pMessage);
                return sMessage;
            }
            else
            {
                return "No message";
            }
        }
    }
}
